require(
		[ "dojo/parser", "dojo/ready", "dijit/registry", "dojo/dom",
				"dojo/dom-form", "dojo/json", "dojo/_base/fx", "dojo/request",
				"dojo/on", "dijit/layout/BorderContainer",
				"dijit/layout/TabContainer", "dijit/layout/ContentPane",
				"dojo/domReady!" ],
		function(parser, ready, registry, dom, domForm, JSON, fx, request, on) {

			var resourceSetting = {
				view : {
					addHoverDom : addHoverDom,
					removeHoverDom : removeHoverDom,
					selectedMulti : false,
					dblClickExpand : dblClickExpand
				},
				data : {
					simpleData : {
						enable : true,
						idKey : "id",
						pIdKey : "pid"
					}
				},
				callback : {
					onClick : bindForm
				}
			};

			function dblClickExpand(treeId, treeNode) {
				return treeNode.level > 0;
			}

			function addHoverDom(treeId, treeNode) {
				var sObj = $("#" + treeNode.tId + "_span");
				// if (treeNode.editNameFlag || $("#addBtn_" +
				// treeNode.id).length > 0)
				// return;
				var type = treeNode.type;
				var id = treeNode.id;
				var buttonStr = "";

				var addApplicationStr = "<span class='button addAppliaction' id='addBtn_"
						+ id
						+ "' title=\"增加应用\" onfocus='this.blur();'></span>";
				var addModuleStr = "<span class='button addModule' id='addBtn_module_"
						+ id
						+ "' title=\"增加模块\" onfocus='this.blur();'></span>";
				var addOperationStr = "<span class='button addOperation' id='addBtn_operation_"
						+ id
						+ "' title=\"增加操作\" onfocus='this.blur();'></span>";
				var deleteNodeStr = "<span class='button deleteNode' id='delBtn_"
						+ id + "' title=\"删除\" onfocus='this.blur();'></span>";
				if ("root" == type) {
					// 根节点
					if ($("#addBtn_" + id).length > 0) {
						return;
					}
					buttonStr = addApplicationStr;
				} else if ("application" == type) {
					if ($("#addBtn_module_" + id).length > 0
							|| $("#delBtn_" + id).length > 0) {
						return;
					}
					buttonStr = addModuleStr + deleteNodeStr;
				} else if ("module" == type) {
					if ($("#addBtn_module_" + id).length > 0
							|| $("#addBtn_operation_" + id).length > 0
							|| $("#delBtn_" + id).length > 0) {
						return;
					}
					buttonStr = addModuleStr + addOperationStr + deleteNodeStr;
				} else if ("operation" == type) {
					if ($("#delBtn_" + id).length > 0) {
						return;
					}
					buttonStr = deleteNodeStr;
				}

				sObj.after(buttonStr);

				var btnAddApplication = $("#addBtn_" + id);
				if (btnAddApplication) {
					btnAddApplication.bind("click", function() {
						var data = {
							pid : treeNode.id,
							type : "application"
						};
						doRequest(treeNode, data, "add.action");
					});
				}
				var btnAddModule = $("#addBtn_module_" + id);
				if (btnAddModule) {
					btnAddModule.bind("click", function() {
						var data = {
							pid : treeNode.id,
							type : "module"
						};
						doRequest(treeNode, data, "add.action");
					});
				}
				var btnAddOperation = $("#addBtn_operation_" + id);
				if (btnAddOperation) {
					btnAddOperation.bind("click", function() {
						var data = {
							pid : treeNode.id,
							type : "operation"
						};
						doRequest(treeNode, data, "add.action");
					});
				}
				var btnDeleteNode = $("#delBtn_" + id);
				if (btnDeleteNode) {
					btnDeleteNode.bind("click", function() {
						removeResource(treeNode.id);
					});
				}

			}

			function doRequest(_treeNode, _data, url) {
				request.post(url, {
					data : _data,
					handleAs : "json"
				}).then(function(response) {
					var zTree = $.fn.zTree.getZTreeObj("resourceTree");
					zTree.addNodes(_treeNode, response);
					var node = zTree.getNodeByParam("id", response.id);
					zTree.selectNode(node);
					clearForm();
					clickNode(node);
				}, function(error) {
					alert(error);
				});
			}

			function removeHoverDom(treeId, treeNode) {
				var id = treeNode.id;
				var btnAddApplication = $("#addBtn_" + id);
				var btnAddModule = $("#addBtn_module_" + id);
				var btnAddOperation = $("#addBtn_operation_" + id);
				var btnDeleteNode = $("#delBtn_" + id);

				if (btnAddApplication) {
					btnAddApplication.unbind().remove();
				}
				if (btnAddModule) {
					btnAddModule.unbind().remove();
				}
				if (btnAddOperation) {
					btnAddOperation.unbind().remove();
				}
				if (btnDeleteNode) {
					btnDeleteNode.unbind().remove();
				}
			}

			function removeResource(_id) {
				request.post("remove.action", {
					handleAs : "json",
					data : {
						id : _id
					}
				}).then(function(response) {
					var success = response.success;
					if ("1" == success) {
						var zTree = $.fn.zTree.getZTreeObj("resourceTree");
						var node = zTree.getNodeByParam("id", _id);
						zTree.removeNode(node);
						clearForm();
					} else {
						alert("删除失败");
					}
				}, function(error) {
					alert(error);
				});
			}

			function bindForm(event, treeId, treeNode, clickFlag) {
				registry.byId("title").set("value", treeNode.title);
				registry.byId("name").set("value", treeNode.name);
				registry.byId("code").set("value", treeNode.code);
				registry.byId("path").set("value", treeNode.path);
				registry.byId("enable").set("value", treeNode.enable);
				registry.byId("id").set("value", treeNode.id);
				registry.byId("pid").set("value", treeNode.pid);
				registry.byId("remark").set("value", treeNode.remark);
				var tabs = registry.byId("infoTab");
				var basePane = registry.byId("basePane");
				tabs.selectChild(basePane);
				bindRoleTree(treeNode.id);
			}
			function clickNode(treeNode) {
				registry.byId("title").set("value", treeNode.title);
				registry.byId("name").set("value", treeNode.name);
				registry.byId("code").set("value", treeNode.code);
				registry.byId("path").set("value", treeNode.path);
				registry.byId("enable").set("value", treeNode.enable);
				registry.byId("id").set("value", treeNode.id);
				registry.byId("pid").set("value", treeNode.pid);
				registry.byId("remark").set("value", treeNode.remark);
				var tabs = registry.byId("infoTab");
				var basePane = registry.byId("basePane");
				tabs.selectChild(basePane);
			}

			function clearForm() {
				registry.byId("title").set("value", "");
				registry.byId("name").set("value", "");
				registry.byId("code").set("value", "");
				registry.byId("path").set("value", "");
				registry.byId("enable").set("value", "");
				registry.byId("id").set("value", "");
				registry.byId("pid").set("value", "");
				registry.byId("remark").set("value", "");
			}

			function bindRoleTree(_resourceId) {
				var zTree = $.fn.zTree.getZTreeObj("roleTree");
				zTree.checkAllNodes(false);
				request.post("getRelatingRole.action", {
					handleAs : "json",
					data:{resourceId:_resourceId}
				}).then(function(_roleCheckData) {
					if (_roleCheckData) {
						for(var i =0; i<_roleCheckData.length; i++) {
							var _node = zTree.getNodeByParam("id",  _roleCheckData[i]);
							zTree.checkNode(_node, true, false);
						}
					}
				}, function(error) {
					alert(error);
				});		
			}
			var roleSetting = {
				check : {
					chkboxType : {
						"Y" : "ps",
						"N" : "ps"
					},
					enable : true
				},
				data : {
					simpleData : {
						enable : true,
						idKey : "id",
						pIdKey : "pid"
					}
				}
			};

			/**
			 * 构建资源树
			 */
			function buildResourceTree() {
				request.post("tree.action", {
					handleAs : "json"
				}).then(
						function(_resourceTreeData) {
							console.log(_resourceTreeData);
							$.fn.zTree.init($("#resourceTree"),
									resourceSetting, _resourceTreeData);
						}, function(error) {
							alert(error);
						});
			}

			/**
			 * 构建角色树
			 */
			function buildRoleTree() {
				request.post("../role/tree.action", {
					handleAs : "json"
				}).then(
						function(_roleTreeData) {
							$.fn.zTree.init($("#roleTree"), roleSetting,
									_roleTreeData);
							var zTree = $.fn.zTree.getZTreeObj("roleTree");
							var rootNode = zTree.getNodeByParam("id", "root");
							rootNode.nocheck = true;
							zTree.updateNode(rootNode);
						}, function(error) {
							alert(error);
						});
			}

			parser.parse();
			ready(function() {
				buildResourceTree();
				buildRoleTree();

				var btnObjSaveResource = registry.byId("btnSave");
				on(btnObjSaveResource, "click", function(evt) {
					var formData = domForm.toJson("resourceForm");
					var formDataObject = JSON.parse(formData);
					request.post("modify.action", {
						handleAs : "json",
						data : formDataObject
					}).then(function(response) {
						alert(response.success);
						var zTree = $.fn.zTree.getZTreeObj("resourceTree");
						var nodes = zTree.getSelectedNodes();
						for ( var key in formDataObject) {
							nodes[0][key] = formDataObject[key];
						}
						zTree.updateNode(nodes[0]);
					}, function(error) {
						alert(error);
					});

				});

				var btnObjReset = registry.byId("btnReset");
				btnObjReset.on("click", function(evt) {
					registry.byId("resourceForm").reset();
				});

				var btnRelatingRoleObj = registry.byId("btnRelatingRole");
				btnRelatingRoleObj.on("click", function(evt) {
					var resourceTreeObj = $.fn.zTree.getZTreeObj("resourceTree");
					var resources = resourceTreeObj.getSelectedNodes();
					if (resources && resources.length > 0) {

						var _resourceId = resources[0].id;

						var zTree = $.fn.zTree.getZTreeObj("roleTree");
						var nodes = zTree.getCheckedNodes(true);
						if (nodes && nodes.length > 0) {
							var roleArray = new Array();
							for ( var i = 0; i < nodes.length; i++) {
								roleArray.push(nodes[i].id);
							}

							var _data = {
								resourceId : _resourceId,
								roleIdList : roleArray
							};

							request.post("relating.action", {
								handleAs : "json",
								data : _data
							}).then(function(response) {

							}, function(error) {
								alert(error);
							});
						} else {
							request.post("cancelRelating.action", {
								handleAs : "json",
								data : {
									resourceId : _resourceId
								}
							}).then(function(response) {

							}, function(error) {
								alert(error);
							});
						}
					}
				});

				setTimeout(function() {
					setTimeout(function() {
						fx.fadeOut({
							node : "loader",
							duration : 300,
							onEnd : function(n) {
								n.style.display = "none";
							}
						}).play();
					}, 100);
				}, 200);
			});
		});